﻿using MiniExcelLibs;
using MobileControlGuru.Src;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace MobileControlGuru.AutoTask
{
    public partial class OperateVariableForm : Form
    {
        public List<OperateParam> operateParams;

        public OperateVariableForm()
        {
            InitializeComponent();
        }
        public OperateVariableForm(TaskOperateTemp taskOperateTemp)
        {
            this.operateParams = taskOperateTemp.VariableParams;

            InitializeComponent();
        }

        private void InitFlowPanel()
        {
            foreach (var item in this.operateParams)
            {
                var opervateitem = new OperateVariableItem(item);
                opervateitem.deleteVariableTempEevnt += ItemDelete;
                this.flowLayoutPanel1.Controls.Add(opervateitem);

            }
        }


        private void OperateVariableForm_Load(object sender, EventArgs e)
        {
            if (this.operateParams != null)
            {
                this.InitFlowPanel();
            }
            //foreach (var item in this.operateParams)
            //{
            //    this.textBoxVariable.Text += item.TempParam + "\r\n";

            //}

        }

        public List<OperateParam> GetOperateParams()
        {
            List<OperateParam> operateParamtemp = new List<OperateParam>();
            //if (!string.IsNullOrEmpty(this.textBoxVariable.Text))
            //{
            //    string[] lines = this.textBoxVariable.Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);


            //    foreach (var item in lines)
            //    {
            //        OperateParam operateParam = new OperateParam();
            //        operateParam.TempParam = item;
            //        operateParamtemp.Add(operateParam);
            //    }


            //}

            foreach (OperateVariableItem item in this.flowLayoutPanel1.Controls)
            {
                OperateParam temp = new OperateParam();
                if (!string.IsNullOrEmpty(item.inputNumberAmount.Text))
                {
                    Console.WriteLine($"{item.inputNumberAmount.Text} -- {item.inputTempParams.Text}");
                    temp.Amount = Convert.ToInt32(item.inputNumberAmount.Text);
                }

              
                //temp.Amount = Convert.ToInt32(item.inputNumberAmount.Value);
                temp.TempParam = item.inputTempParams.Text;
                operateParamtemp.Add(temp);
            }

            return operateParamtemp;
        }
        private void btnOK_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            // 使用OpenFileDialog让用户选择JSON文件
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "JSON files (*.json)|*.json",
                DefaultExt = "json"
            };

            // 如果用户选择了文件并点击了“打开”
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    // 读取JSON文件的内容
                    string jsonFilePath = openFileDialog.FileName;
                    string jsonData = File.ReadAllText(jsonFilePath);

                    // 反序列化JSON字符串到对象列表
                    List<OperateParam> dataList = JsonConvert.DeserializeObject<List<OperateParam>>(jsonData);

                    // 使用dataList中的数据
                    // 例如，将其显示在DataGridView或其他控件中
                    this.operateParams = dataList;
                    this.InitFlowPanel();  
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导入失败：{ex.Message}");
                }
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            List<OperateParam> list = GetOperateParams();

            // 序列化数据到JSON字符串
            string jsonData = JsonConvert.SerializeObject(list, Formatting.Indented);
            // 创建SaveFileDialog实例并配置
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "JSON (*.json)|*.json|所有文件 (*.*)|*.*";
            saveFileDialog.Title = "多参数";
            saveFileDialog.FileName = $"多参数批量数据_{DateTime.Now.ToString("yyyyMMddHHmmss")}"; // 默认文件名

            // 显示保存对话框并获取用户选择
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {


                try
                {
                    File.WriteAllText(saveFileDialog.FileName, jsonData);

                    MessageBox.Show("数据导出成功！");
                }
                catch (Exception ex)
                {
                    // 处理文件写入过程中的异常
                    MessageBox.Show($"导出失败：{ex.Message}");
                }
            }
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            var edit = new OperateVariableItem();
            edit.deleteVariableTempEevnt += ItemDelete;

            this.flowLayoutPanel1.Controls.Add(edit);
            UpdateItemIndex();
        }
        public void ItemDelete(int index)
        {
            UpdateItemIndex();
        }
        private void UpdateItemIndex()
        {
            int i = 0;
            foreach (OperateVariableItem c in this.flowLayoutPanel1.Controls)
            {
                c.SetIndex(++i);
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.operateParams = null;
            this.flowLayoutPanel1.Controls.Clear();
        }

        private void buttonImportExcel_Click(object sender, EventArgs e)
        {
            // 使用OpenFileDialog让用户选择JSON文件
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "Excel files (*.json)|*.xlsx",
                DefaultExt = "xlsx"
            };

            // 如果用户选择了文件并点击了“打开”
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    // 读取JSON文件的内容
                    string jsonFilePath = openFileDialog.FileName;
                  
                    var rows = MiniExcel.Query(jsonFilePath).ToList();
                    List<OperateParam> dataList = new List<OperateParam>();
                    for (int i = 1; i < rows.Count; i++)//跳过首行
                    {
                        OperateParam operateParam = new OperateParam()
                        {
                            TempParam = DynamicStringHelper.DynamicToString(rows[i].A),
                            Amount = int.Parse(DynamicStringHelper.DynamicToString(rows[i].B))
                        };

                        dataList.Add(operateParam);
                        Console.WriteLine($"TempParam: {rows[i].A}, Amount: {rows[i].B}");
                    }

                    //string jsonData = File.ReadAllText(jsonFilePath);

                    //// 反序列化JSON字符串到对象列表
                    //List<OperateParam> dataList = JsonConvert.DeserializeObject<List<OperateParam>>(jsonData);

                    //// 使用dataList中的数据
                    //// 例如，将其显示在DataGridView或其他控件中
                    this.operateParams = dataList;
                    this.InitFlowPanel();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导入失败：{ex.Message}");
                }
            }
        }
       

        private void buttonExportExcel_Click(object sender, EventArgs e)
        {
            List<OperateParam> list = GetOperateParams();

            // 序列化数据到JSON字符串
            //string jsonData = JsonConvert.SerializeObject(list, Formatting.Indented);
            // 创建SaveFileDialog实例并配置
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "xlsx (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*";
            saveFileDialog.Title = "多参数";
            saveFileDialog.FileName = $"多参数批量数据_{DateTime.Now.ToString("yyyyMMddHHmmss")}"; // 默认文件名

            // 显示保存对话框并获取用户选择
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {


                try
                {
                    var values = new List<Dictionary<string, object>>();
                    foreach (var item in list)
                    {
                        var dic = new Dictionary<string, object> { { "TempParam", item.TempParam }, { "Amount", item.Amount } };
                        values.Add(dic);

                    }
                    //File.WriteAllText(saveFileDialog.FileName, jsonData);
                    MiniExcel.SaveAs(saveFileDialog.FileName, values);
                    MessageBox.Show("数据导出成功！");
                }
                catch (Exception ex)
                {
                    // 处理文件写入过程中的异常
                    MessageBox.Show($"导出失败：{ex.Message}");
                }
            }
        }
    }
}
